<template>
  <div class="article-management">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h2>文章管理</h2>
          <el-button type="primary" @click="createNewArticle">
            <el-icon><Plus /></el-icon>
            新建文章
          </el-button>
        </div>
      </template>
      
      <div class="filters">
        <el-select 
          v-model="statusFilter" 
          @change="loadArticles" 
          placeholder="筛选状态"
          style="width: 150px"
        >
          <el-option label="全部状态" value=""></el-option>
          <el-option label="草稿" value="DRAFT"></el-option>
          <el-option label="已发布" value="PUBLISHED"></el-option>
          <el-option label="已归档" value="ARCHIVED"></el-option>
        </el-select>
        
        <el-input
          v-model="searchKeyword"
          placeholder="搜索文章标题或内容"
          @input="searchArticles"
          clearable
          style="max-width: 400px"
        >
          <template #prefix><el-icon><Search /></el-icon></template>
        </el-input>
      </div>
      
      <el-table 
        :data="articles" 
        stripe
        border
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="130" />
        <el-table-column label="标题" min-width="230px">
          <template #default="{ row }">
            <div class="title-cell">
              <div class="title">{{ row.title }}</div>
              <div class="content-preview">{{ getContentPreview(row.content) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="作者/时间" width="180">
          <template #default="{ row }">
            <div class="author-time-cell">
              <div class="author">
                <el-icon><User /></el-icon>
                <span>{{ getAuthorName(row.authorId) }}</span>
              </div>
              <div class="time">
                <el-icon><Clock /></el-icon>
                <span>{{ formatDate(row.createdAt) }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="分类" width="150">
          <template #default="{ row }">
            <div v-if="row.categories" class="category-tags">
              <el-tag 
                v-for="label in getCategoryLabels(row.categories)" 
                :key="label"
                size="small"
                style="margin-right: 4px; margin-bottom: 2px;"
              >
                {{ label }}
              </el-tag>
            </div>
            <span v-else class="no-category">未分类</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="210px" >
          <template #default="{ row }">
            <el-button type="info" link size="small" @click="viewArticle(row)">
              查看
            </el-button>
            <el-button 
              v-if="canEdit(row)" 
              type="warning" 
              link 
              size="small" 
              @click="editArticle(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="row.status === 'DRAFT'" 
              type="success" 
              link 
              size="small" 
              @click="publishArticle(row.id)"
            >
              发布
            </el-button>
            <el-button 
              v-if="row.status === 'PUBLISHED'" 
              link 
              size="small" 
              @click="archiveArticle(row.id)"
            >
              归档
            </el-button>
            <el-popconfirm
              v-if="canDelete(row)"
              title="确定要删除这篇文章吗？"
              @confirm="deleteArticle(row.id)"
            >
              <template #reference>
                <el-button type="danger" link size="small">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 文章编辑/创建对话框 -->
    <el-dialog
      v-model="showCreateForm"
      :title="editingArticle ? '编辑文章' : '新建文章'"
      width="800px"
    >
      <el-form
        :model="articleForm"
        label-width="80px"
      >
        <el-form-item label="标题" required>
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" />
        </el-form-item>
        
        <el-form-item label="内容" required>
          <el-input 
            v-model="articleForm.content" 
            type="textarea"
            placeholder="请输入文章内容"
            :rows="10"
          />
        </el-form-item>
        
        <el-form-item label="作者" required>
          <el-select v-model="articleForm.authorId" placeholder="请选择作者" style="width: 100%">
            <el-option 
              v-for="user in users" 
              :key="user.id" 
              :label="user.fullName || user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="分类">
          <el-select 
            v-model="articleForm.categories" 
            multiple 
            placeholder="请选择分类（可多选）" 
            style="width: 100%"
          >
            <el-option 
              v-for="category in categories" 
              :key="category.dictCode" 
              :label="category.dictLabel"
              :value="category.dictValue"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-radio-group v-model="articleForm.status">
            <el-radio label="DRAFT">草稿</el-radio>
            <el-radio label="PUBLISHED">已发布</el-radio>
            <el-radio label="ARCHIVED">已归档</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="saveArticle" :loading="loading">保存</el-button>
      </template>
    </el-dialog>
    
    
  </div>
</template>

<script>
import { Plus, Search, User, Clock } from '@element-plus/icons-vue'
import { articleAPI } from '@api/article.js'
import { userAPI } from '@api/user.js'
import { dictAPI } from '@api/dict.js'
import { ElMessage } from 'element-plus'

export default {
  name: 'ArticleManagement',
  components: {
    Plus,
    Search,
    User,
    Clock
  },
  data() {
    return {
      articles: [],
      users: [],
      categories: [],
      loading: false,
      statusFilter: '',
      searchKeyword: '',
      showCreateForm: false,
      editingArticle: null,
      articleForm: {
        title: '',
        content: '',
        authorId: '',
        status: 'DRAFT',
        categories: []
      }
    }
  },
  computed: {
    currentUser() {
      return this.$store.state.user
    }
  },
  mounted() {
    this.loadArticles()
    this.loadUsers()
    this.loadCategories()
  },
  methods: {
    async loadArticles() {
      this.loading = true
      try {
        const response = await articleAPI.getAllArticles()
        if (response.data.success) {
          this.articles = response.data.data
        }
      } catch (error) {
        console.error('加载文章失败:', error)
        ElMessage.error('加载文章失败')
      } finally {
        this.loading = false
      }
    },
    
    async loadUsers() {
      try {
        const response = await userAPI.getAllUsers()
        if (response.data.success) {
          this.users = response.data.data
        }
      } catch (error) {
        console.error('加载用户失败:', error)
      }
    },
    
    async loadCategories() {
      try {
        const response = await dictAPI.getArticleCategories()
        if (response.data.success) {
          this.categories = response.data.data
        }
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    },
    
    async searchArticles() {
      if (!this.searchKeyword.trim()) {
        this.loadArticles()
        return
      }
      
      this.loading = true
      try {
        const response = await articleAPI.searchArticles(this.searchKeyword)
        if (response.data.success) {
          this.articles = response.data.data
        }
      } catch (error) {
        console.error('搜索文章失败:', error)
        ElMessage.error('搜索文章失败')
      } finally {
        this.loading = false
      }
    },
    
    createNewArticle() {
      // 清空表单数据
      this.articleForm = {
        title: '',
        content: '',
        authorId: '',
        status: 'DRAFT',
        categories: []
      }
      this.editingArticle = null
      this.showCreateForm = true
    },
    
    viewArticle(article) {
      console.log('查看文章:', article)
      // 在新标签页中打开文章预览
      const previewUrl = `/preview/${article.id}`
      window.open(previewUrl, '_blank')
    },
    
    
    editArticle(article) {
      console.log('编辑文章:', article)
      // 跳转到编辑页面
      this.$router.push(`/edit/${article.id}`)
    },
    
    
    async saveArticle() {
      if (!this.articleForm.title || !this.articleForm.content || !this.articleForm.authorId) {
        ElMessage.warning('请填写所有必填项')
        return
      }
      
      this.loading = true
      
      try {
        // 处理分类数据，将数组转换为逗号分隔的字符串
        const formData = {
          ...this.articleForm,
          categories: this.articleForm.categories.join(',')
        }
        
        if (this.editingArticle) {
          const response = await articleAPI.updateArticle(this.editingArticle.id, formData)
          if (response.data.success) {
            ElMessage.success('更新成功')
            this.loadArticles()
            this.closeModal()
          }
        } else {
          const response = await articleAPI.createArticle(formData)
          if (response.data.success) {
            ElMessage.success('创建成功')
            this.loadArticles()
            this.closeModal()
          }
        }
      } catch (error) {
        console.error('保存文章失败:', error)
        ElMessage.error('保存失败')
      } finally {
        this.loading = false
      }
    },
    
    async publishArticle(id) {
      try {
        const response = await articleAPI.publishArticle(id)
        if (response.data.success) {
          ElMessage.success('发布成功')
          this.loadArticles()
        }
      } catch (error) {
        console.error('发布文章失败:', error)
        ElMessage.error('发布失败')
      }
    },
    
    async archiveArticle(id) {
      try {
        const response = await articleAPI.archiveArticle(id)
        if (response.data.success) {
          ElMessage.success('归档成功')
          this.loadArticles()
        }
      } catch (error) {
        console.error('归档文章失败:', error)
        ElMessage.error('归档失败')
      }
    },
    
    async deleteArticle(id) {
      try {
        const response = await articleAPI.deleteArticle(id)
        if (response.data.success) {
          ElMessage.success('删除成功')
          this.loadArticles()
        }
      } catch (error) {
        console.error('删除文章失败:', error)
        ElMessage.error('删除失败')
      }
    },
    
    closeModal() {
      this.showCreateForm = false
      this.editingArticle = null
      this.articleForm = {
        title: '',
        content: '',
        authorId: '',
        status: 'DRAFT',
        categories: []
      }
    },
    
    canEdit(article) {
      return this.currentUser && 
             (this.currentUser.id === article.authorId || this.currentUser.isAdmin)
    },
    
    canDelete(article) {
      return this.currentUser && this.currentUser.isAdmin
    },
    
    getAuthorName(authorId) {
      const user = this.users.find(u => u.id === authorId)
      return user ? (user.fullName || user.username) : '未知'
    },
    
    getStatusText(status) {
      const statusMap = {
        'DRAFT': '草稿',
        'PUBLISHED': '已发布',
        'ARCHIVED': '已归档'
      }
      return statusMap[status] || status
    },
    
    getStatusType(status) {
      const typeMap = {
        'DRAFT': '',
        'PUBLISHED': 'success',
        'ARCHIVED': 'warning'
      }
      return typeMap[status] || ''
    },
    
    getContentPreview(content) {
      if (!content) return ''
      return content.length > 100 ? content.substring(0, 100) + '...' : content
    },
    
    formatDate(dateString) {
      if (!dateString) return ''
      return new Date(dateString).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    getCategoryLabels(categories) {
      if (!categories) return []
      const categoryList = categories.split(',').map(c => c.trim())
      return categoryList.map(categoryValue => {
        const category = this.categories.find(c => c.dictValue === categoryValue)
        return category ? category.dictLabel : categoryValue
      })
    }
  }
}
</script>

<style scoped>
.article-management {
  padding: 24px;
  width: calc(100% - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.filters {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.title-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 4px 0;
}

.title-cell:hover .title {
  color: #409eff;
  transition: color 0.3s ease;
}

.title {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
  font-weight: 600;
  color: #ffffff;
  font-size: 14px;
  line-height: 1.5;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.content-preview {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
  font-size: 12px;
  color: #c0c4cc;
  line-height: 1.6;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
}


.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.no-category {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
  color: #909399;
  font-style: italic;
  font-size: 12px;
  line-height: 1.4;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
}

.author-time-cell {
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding: 4px 0;
}

.author,
.time {
  display: flex;
  align-items: center;
  gap: 4px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
  font-size: 12px;
  line-height: 1.4;
}

.author {
  color: #ffffff;
  font-weight: 500;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
}

.time {
  color: #c0c4cc;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
}

.author .el-icon,
.time .el-icon {
  font-size: 12px;
  opacity: 0.7;
}

</style>
